import router from './router/index'
import Store from './store/index'
import Nprogress from 'nprogress' // 模拟进度条效果
import 'nprogress/nprogress.css'

// 白名单（不需要token）
const writePath = ['/login', '/404']

// 前置路由守卫
router.beforeEach(async(to, from, next) => {
  Nprogress.start() // 开启进度条
  if (Store.state.user.token) {
    if (to.path.toLowerCase() === '/login') {
      next('/')
    } else {
      if (Store.state.user.userInfo.userId) {
        next()
      } else {
        await Store.dispatch('user/getUserinfo')
        // addRouters添加的路由不能立即使用，要再一次路由守卫
        next(to.fullPath)
      }
    }
  } else {
    if (writePath.includes(to.path.toLowerCase())) {
      next()
    } else {
      next('/login?redirect=' + to.fullPath)
    }
  }
  Nprogress.done() // 关闭进度条
})

// 后置路由守卫
router.afterEach(() => {
  Nprogress.done() // 关闭进度条
})
